<?php

App::uses('AppController', 'Controller');

/**
 * HProducts Controller
 *
 * @property HProduct $HProduct
 */
class HProductsController extends AppController {

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->HProduct->recursive = 0;

        if ((!isset($this->request->data['from']) && !isset($this->request->data['to'])) ||
                (empty($this->request->data['from']) && empty($this->request->data['to']))) {

            $this->paginate = array('order' => 'HProduct.date DESC');
            $this->set('hProducts', $this->paginate());
        } else {

            $fechaInicio = date("Y-m-d", strtotime(trim($this->request->data('from'))));
            $fechaInicio .=' 00:00:00';
            if (empty($this->request->data['to'])) {
                $fechaFin = date("Y-m-d", strtotime(trim($this->request->data('from'))));
            } else {
                $fechaFin = date("Y-m-d", strtotime(trim($this->request->data('to'))));
            }
            $fechaFin .= ' 24:00:00';

            $this->paginate = array('order' => 'HProduct.date DESC');
            $this->set('hProducts', $this->paginate(array('AND' => array('HProduct.date >=' => $fechaInicio,
                            'HProduct.date <=' => $fechaFin))
                    ));
        }
    }

    public function export($from = null, $to = null) {
        App::uses('Folder', 'Utility');
        App::uses('File', 'Utility');

        $name = 'gastos_compras_' . date('dmY') . '.csv';
        $csv_file = 'files/gastos/' . $name;
        $csv = "";

        if ((!isset($from) && !isset($to)) ||
                (empty($from) && empty($to))) {

            $contacts = $this->HProduct->find('all', array('order' => 'HProduct.date desc') );
        } else {


            $fechaInicio = date("Y-m-d", strtotime(trim($from)));
            $fechaInicio .=' 00:00:00';

            if (empty($to)) {

                $fechaFin = date("Y-m-d", strtotime(trim($from)));
            } else {

                $fechaFin = date("Y-m-d", strtotime(trim($to)));
            }

            $fechaFin .= ' 24:00:00';

            $contacts = $this->HProduct->find('all', array(
                'conditions' => array(
                    'AND' => array('HProduct.date >=' => $fechaInicio, 'HProduct.date <=' => $fechaFin)
                ), array('order' => 'HProduct.date desc')
                    ));
        }


        $csv .= "Resumen de Productos Comprados\n";
        $csv .= "Punto de Venta; Producto; Fecha; Precio de Compra($); Cantidad; Total Parcial\n";
        $total_general = 0;


        foreach ($contacts as $key => $contact) {
            $csv .= "{$contact['Shop']['name']};";
            $csv .= "{$contact['Product']['name']};";

            $datetime = date('d/m/Y H:i:s', strtotime($contact['HProduct']['date']));
            $csv .= "{$datetime};";

            $csv .= "{$contact['HProduct']['purchase_price']};";
            $csv .= "{$contact['HProduct']['quantity']};";

//      Calculo total parcial y acumulo para total final
            $total_parcial = $contact['HProduct']['quantity'] * $contact['HProduct']['purchase_price'];
            $total_general += $total_parcial;

            $csv .= "{$total_parcial}\n";
        }
        $csv .= ";;;;Total General;" . $total_general;


        //Generamos el csv de todos los datos
        $file = new File($csv_file, true, 0777);
        $file->create();
//    if (!$file->open("w")) {
//      $this->Session->setFlash(__('No se puede abrir el archivo'));
//      $this->redirect(array('action' => 'index'));
//    }
        if (!$file->write(utf8_decode($csv))) {
            $this->Session->setFlash(__('No se puede escribir en el archivo'));
            $this->redirect(array('action' => 'index'));
        }
        $file->close();

        chmod('files/gastos/' . $name, 0777);

        $this->redirect('/files/gastos/' . $name);
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->HProduct->exists($id)) {
            throw new NotFoundException(__('Invalid h product'));
        }
        $options = array('conditions' => array('HProduct.' . $this->HProduct->primaryKey => $id));
        $this->set('hProduct', $this->HProduct->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->HProduct->create();
            if ($this->HProduct->save($this->request->data)) {
                $this->Session->setFlash(__('La compra ha sido creada exitosamente'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La compra NO ha sido creada. Intente nuevamente.'));
            }
        }
        $shops = $this->HProduct->Shop->find('list');
        $products = $this->HProduct->Product->find('list');
        $this->set(compact('shops', 'products'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null, $quantityOld = null) {

        $this->HProduct->id = $id;

        Configure::write('quantityOld', $quantityOld);


        if (!$this->HProduct->exists($id)) {
            throw new NotFoundException(__('Invalid h product'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->HProduct->save($this->request->data) &&
                    $this->restoreStock($this->request->data['HProduct']['shop_id'], $this->request->data['HProduct']['product_id'], ( Configure::read('quantityOld') - $this->request->data['HProduct']['quantity']))) {
                $this->Session->setFlash(__('La compra ha sido guardada exitosamente'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La compra NO ha sido guardada. Intente Nuevamente.'));
            }
        } else {
            $options = array('conditions' => array('HProduct.' . $this->HProduct->primaryKey => $id));
            $this->request->data = $this->HProduct->find('first', $options);
        }
        $shops = $this->HProduct->Shop->find('list');
        $products = $this->HProduct->Product->find('list');
        $this->set(compact('shops', 'products'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null, $shop_id = null, $product_id = null, $quantity = null) {
        $this->HProduct->id = $id;
        if (!$this->HProduct->exists()) {
            throw new NotFoundException(__('Invalid h product'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->HProduct->delete() && $this->restoreStock($shop_id, $product_id, ($quantity * -1))) {
            $this->Session->setFlash(__('La compra ha sido eliminada exitosamente'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('La compra NO ha sido eliminada'));
        $this->redirect(array('action' => 'index'));
    }

    public function restoreStock($shop_id = null, $product_id = null, $quantityProduct = null) {

//        con el listado verifico stock y descuento en el Punto de Venta correspondiente
        $this->loadModel('ProductShop');
        $productShop = $this->ProductShop->find('first', array('fields' => array(
                'ProductShop.current_stock', 'ProductShop.id',), 'conditions' => array(
                'ProductShop.product_id' => $product_id,
                'ProductShop.shop_id' => $shop_id,
                )));

        $this->ProductShop->id = $productShop['ProductShop']['id'];

        $update_stock = ($productShop['ProductShop']['current_stock'] - $quantityProduct);
        if ($this->ProductShop->saveField('current_stock', $update_stock))
            return true;
    }

}
